package com.xxxx.portal.controller;


import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xxxx.common.result.BaseResult;
import com.xxxx.portal.service.impl.CookieService;
import com.xxxx.sso.pojo.Admin;
import com.xxxx.sso.service.IAdminService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping("/user")
public class PortalController {

    @Reference(version = "1.0")
    private IAdminService iAdminService;


    @Autowired
    private CookieService cookieService;

    @RequestMapping("/login")
    @ResponseBody
    public BaseResult login(Admin admin, HttpServletRequest request , HttpServletResponse response){

        //登录成功生成ticket票据
        String ticket = iAdminService.login(admin);

        if (!StringUtils.isBlank(ticket)){
            boolean result = cookieService.setCookie(request, response, ticket);

            //将用户信息存入session中，用于页面显示
            request.getSession().setAttribute("user",admin);

            if (result) return BaseResult.success();

        }

        return  BaseResult.error();
    }


    //用户退出
    @RequestMapping("/logout")
    public  String logout(HttpServletRequest request , HttpServletResponse response ){
        //删除票据
        String ticket = cookieService.getCookie(request);
        iAdminService.logout(ticket);
        //删除session
        request.getSession().removeAttribute("user");
        //删除cookie
        cookieService.deleteCookie(request,response);
        //返回登录页面
        return  "login";
    }
}